/*
 * Created by: Peter Weissbrod
 * Created: Monday, January 21, 2008
 */
using System;
using System.Text.RegularExpressions;
using PostSharp.Laos;
using PostSharp.UserSamples.Exceptions;
using PostSharp.UserSamples.Utils;

namespace PostSharp.UserSamples.Validators
{
    /// <summary>
    /// Throws ValidationException for any string that do not match the defined expression pattern
    /// </summary>
    [Serializable]
    public class RegExValidator:OnMethodBoundaryAspect
    {
        /// <summary>
        /// The regular expression pattern
        /// </summary>
        public string RegularExpression
        {
            get;
            set;
        }
        /// <summary>
        /// Restrict to public property setters of type string
        /// </summary>
        /// <param name="method"></param>
        /// <returns></returns>
        public override bool CompileTimeValidate(System.Reflection.MethodBase method)
        {
            return CompileTimeValidateScenario.ValidateForPublicPropertySetter(method) &&
                   CompileTimeValidateScenario.RestrictPropertySetterToSpecificType(method, typeof(string));
        }
        /// <summary>
        /// validate before the property setter occurs
        /// </summary>
        /// <param name="eventArgs"></param>
        public override void OnEntry(MethodExecutionEventArgs eventArgs)
        {
            if (eventArgs.GetArguments() != null)
            {
                string value = (string) eventArgs.GetArguments()[0];
                if (!Regex.IsMatch(value,RegularExpression))
                    throw new ValidationException(
                        "Value did not match the specified regular expression [" + RegularExpression + "]", eventArgs);
            }
            base.OnEntry(eventArgs);
        }
    }
}